package com.jsmtr.rms.controller;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.BaseRole;
import com.jsmtr.rms.entity.LayuiDataTableResultBean;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.entity.HRSchoolUsers;
import com.jsmtr.rms.service.ISchoolService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.DateTools;
import com.jsmtr.rms.utils.EnumTools;
import com.jsmtr.rms.utils.StringTools;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/schooluser")
public class SysSchoolController {

    @Resource
    private IUtilService utilService;

    @Resource
    private ISchoolService schoolService;

    //首页
    @RequestMapping("/")
    public String Index() {
        return "/SysAdmin/school/index";
    }

    //获得账户信息
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getlists", method = RequestMethod.POST)
    public void GetList(HttpServletRequest request, HttpServletResponse response) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            int state = Integer.parseInt(request.getParameter("state"));
            String key = request.getParameter("key").trim();

            Map<String, Object> map = schoolService.getSchools(page, perpage, state, key);

            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (HRSchoolUsers user : (List<HRSchoolUsers>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id=\"cb_" + user.getId() + "\" /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + user.getUcode() + "</td>");
                    result.append("<td>" + user.getUname() + "</td>");
                    result.append("<td>" + user.getUtel() + "</td>");
                    result.append("<td>" + (user.getLogintime() == null ? "" : DateTools.toLenStr(user.getLogintime())) + "</td>");
                    if (user.getUstate() == 0) {
                        result.append("<td class='false'>");
                    } else {
                        result.append("<td class='true'>");
                    }
                    result.append("<span>" + EnumTools.State.values()[user.getUstate()] + "</span></td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='6'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getlistsLayuiJson")
    public LayuiDataTableResultBean getlistsLayuiJson(HttpServletRequest request, HttpServletResponse response) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            int state = -1;
            try {
                state = Integer.parseInt(request.getParameter("state"));
            } catch (NumberFormatException ignored) {

            }
            String key = request.getParameter("key");
            if (key == null) {
                key = "";
            }

            Map<String, Object> map = schoolService.getSchools(page, limit, state, key);
            List<Object> list = (List<Object>)map.get("list");
            JSONArray jsonArray = new JSONArray();
            for (Object item :
                    list) {
                JSONObject jsonObject = JSONObject.fromObject(item);
                HRSchoolUsers itm = (HRSchoolUsers)item;
                jsonObject.put("lastlogintime"
                        , itm.getLogintime() == null ? "" : DateTools.toLenStr(itm.getLogintime()));
                jsonObject.put("stateS", itm.getUstate() != 0);
                if (itm.getLogintime() == null) {
                    jsonObject.replace("logintime", "");
                }
                jsonArray.add(jsonObject);
            }
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(jsonArray);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    //添加账号
    @RequestMapping("/add")
    public String Add() {
        return "/SysAdmin/school/add";
    }

    //添加账号
    @RequestMapping(value = "AddAction", method = RequestMethod.POST)
    public void AddAction(HttpServletRequest request, HttpServletResponse response, HRSchoolUsers user) {
        try {
            if (!schoolService.hasSchool(user.getUcode())) {
                user.setId(UUID.randomUUID().toString());
                user.setUstate(EnumTools.State.启用.ordinal());
                user.setUpwd(StringTools.GetMD5Code(user.getUpwd()));
                utilService.addObject(user);
                utilService.printJsonResult(true, "添加成功！", "no", response);
            } else {
                utilService.printJsonResult(false, "该账户已存在！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //修改账号
    @RequestMapping("/edit")
    public String Edit(HttpServletRequest request, Model model) {
        try {
            HRSchoolUsers user = schoolService.getSchool(request.getParameter("id").trim());
            model.addAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/SysAdmin/school/edit";
    }

    //修改账号
    @RequestMapping(value = "EditAction", method = RequestMethod.POST)
    public void EditAction(HttpServletRequest request, HttpServletResponse response, HRSchoolUsers user) {
        try {
            HRSchoolUsers nuser = schoolService.getSchool(user.getId());
            nuser.setUtel(user.getUtel());
            int pwd = Integer.parseInt(request.getParameter("pwd").trim());
            if (pwd == 1) {
                nuser.setUpwd(StringTools.GetMD5Code(user.getUpwd()));
            }
            utilService.editObject(nuser);
            utilService.printJsonResult(true, "操作成功！", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //禁用/启用
    @RequestMapping(value = "/DelAction", method = RequestMethod.POST)
    public void DelAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            HRSchoolUsers user = schoolService.getSchool(request.getParameter("id").trim());
            if (user.getUstate() == EnumTools.State.启用.ordinal()) {
                user.setUstate(EnumTools.State.禁用.ordinal());
            } else {
                user.setUstate(EnumTools.State.启用.ordinal());
            }
            utilService.editObject(user);
            utilService.printJsonResult(true, "操作成功！", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }
}
